package com.hfy.kandian.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hfy.kandian.entity.User;
import com.hfy.kandian.entity.Vip;
import com.hfy.kandian.mapper.VipMapper;
import com.hfy.kandian.service.VipService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author HAN XIAOYANG
 * @since 2020-12-30
 */
@Service
public class VipServiceImpl extends ServiceImpl<VipMapper, Vip> implements VipService {

    @Autowired
    private VipMapper vipMapper;

    @Override
    public int beVip(int userId, int dateLen) {
        /**检测表中是否有记录：
         *      如果没有，直接添加一行数据
         *      如果有,检测是否为过期状态：
         *              如果是：due_date=当前日期+dateLen
         *              如果否：due_date+=当前日期
         *
         *
         *      */
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",userId);
        Vip theVip = vipMapper.selectOne(queryWrapper);
        Calendar calendar = Calendar.getInstance();
        if(theVip==null){
            calendar.setTime(new Date());
            calendar.add(Calendar.MONTH,dateLen);
            theVip = new Vip();
            theVip.setUserId(userId).setDueDate(calendar.getTime());
            return vipMapper.insert(theVip);
        }else{
            if(theVip.getDueDate().before(new Date())){//VIP已过期
                calendar.setTime(new Date());
                calendar.add(Calendar.MONTH,dateLen);
                theVip.setDueDate(calendar.getTime());
                vipMapper.updateById(theVip);
            }else{//是VIP用户
                calendar.setTime(theVip.getDueDate());
                calendar.add(Calendar.MONTH,dateLen);
                theVip.setDueDate(calendar.getTime());
                return vipMapper.updateById(theVip);
            }
        }
        return 0;
    }

    @Override
    public int isVip(int userId) {
        /**
         * 判断是否在VIP表中：
         *      否：不是VIP，返回0
         *      是：判断是否过期：
         *          是：过期VIP，返回1
         *          不是：为VIP，返回2
         * */
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",userId);
        Vip theVip = vipMapper.selectOne(queryWrapper);
        if(theVip==null){
            return 0;
        }else{
            if(theVip.getDueDate().before(new Date())){
                return 1;
            }else{
               return 2;
            }
        }
    }
}
